package com;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by bruce on 2016/5/22.
 */
public class JSONParser {

    public static <T> Object parse(String jsonString, T type) throws Exception {

        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.readValue(jsonString, new TypeReference<T>() { });
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("exception.jsonparse.error");
        }
    }

    public static String stringify(Object object) throws JsonProcessingException{
        String result = "";
        ObjectMapper mapper = new ObjectMapper();
        result = mapper.writeValueAsString(object);
        return result;
    }

    public static HashMap<String, Object> introspect(Object obj) throws Exception {
        HashMap<String, Object> result = new HashMap<String, Object>();
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            String key = pd.getName();

            if(key.equals("class")) {
                continue;
            }

            Method reader = pd.getReadMethod();
            if (reader != null) {

                Object value = reader.invoke(obj);

                if(value != null && (value.getClass() == ArrayList.class || value.getClass() == List.class || value.getClass() == LinkedList.class)) {
                    List<?> list = (List<?>) value;
                    ArrayList<HashMap<String, Object>> array = new ArrayList<HashMap<String, Object>>();
                    for(Object item : list) {
                        array.add(introspect(item));
                    }
                    value = array;
                }

                result.put(key, value);
            }
        }
        return result;
    }
}
